#include <arpa/inet.h>
#include <cstring>
#include <iostream>
#include <sys/select.h>
#include <sys/socket.h>
#include <unistd.h>
#include <fcntl.h> 
int main() {
    // 1. 创建 TCP 监听套接字
    int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
    sockaddr_in addr{};
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(8080);
    bind(listen_fd, (sockaddr *)&addr, sizeof(addr));
    listen(listen_fd, 5);

    // 2. 把 listen_fd 设为非阻塞（可选，方便演示）
    fcntl(listen_fd, F_SETFL, O_NONBLOCK);

    std::cout << "Listening on 0.0.0.0:8080, press q+Enter to quit\n";

    while (true) {
        fd_set rfds;
        FD_ZERO(&rfds);

        // 3. 把要监听的 fd 放进 rfds
        FD_SET(STDIN_FILENO, &rfds);  // 监听终端
        FD_SET(listen_fd, &rfds);     // 监听新连接

        int max_fd = std::max(STDIN_FILENO, listen_fd);

        // 4. 调用 select（这里不设置超时，一直阻塞）
        int ready = select(max_fd + 1, &rfds, nullptr, nullptr, nullptr);
        if (ready < 0) {
            perror("select");
            break;
        }

        // 5. 轮询检查是谁就绪
        if (FD_ISSET(STDIN_FILENO, &rfds)) {
            char buf[128];
            if (fgets(buf, sizeof(buf), stdin)) {
                if (buf[0] == 'q') {
                    std::cout << "Quit by user\n";
                    break;
                }
            }
        }

        if (FD_ISSET(listen_fd, &rfds)) {
            sockaddr_in client_addr{};
            socklen_t len = sizeof(client_addr);
            int conn_fd = accept(listen_fd, (sockaddr *)&client_addr, &len);
            if (conn_fd >= 0) {
                std::cout << "New connection from "
                          << inet_ntoa(client_addr.sin_addr) << ":"
                          << ntohs(client_addr.sin_port) << "\n";
                close(conn_fd);  // 简单示例：直接关闭
            }
        }
    }

    close(listen_fd);
    return 0;
}